Javascript mouseover effects on table rows using jQuery


Introduction
Lately I’ve been getting into jQuery. On first sight the syntax can look a bit strange, but I get it now – for the most part, that is. On a related note, for a while now I’ve been “wondering” about how you do the mouseover effects you sometimes see on table rows. I’m talking about the effects where you move your mouse over a cell in table row and then the full row’s background colour changes to give the effect of highlighting the full row for selection. I really haven’t given it much thought, but I recently came across some code in a company application that got me thinking about it again so I decided time was right for to take a closer look.

Code
Originally, before the use of jQuery, your markup would look something like this:



   <table>
      <tbody>
         <tr>
            <td>some table cell content here</td>
         </tr>
         <tr style="cursor:pointer;">
            <td>some table cell content here</td>
         </tr>
         <tr>
            ...
            more rows and cells containing more of the same here
            ...
         </tr>
      </tbody>
   </table>


You’ll notice the obtrusive JavaScript event handling code on lines 5 to 8 and 11 to 14. This code repeats itself on every row of the table which is just annoying. The only difference between the code attached to the individual table rows is the obvious onclick event handler (here a simple alert message) which should simulate some functionality specific to a click on that unique row. As a whole this use of Javascript makes the markup somewhat more difficult to read and generally untidy. Of course it is usually the backend server code creating this kind of code in a for-loop or similar – nobody writes this stuff by hand, but that’s not the point.
So how can you use jQuery to replace this mess? The following shows a first attempt of a replacement using jQuery.



   
   
      $(function() {
         $('table tbody tr').mouseover(function() {
            $(this).addClass('selectedRow');
         }).mouseout(function() {
            $(this).removeClass('selectedRow');
         }).click(function() {
            alert($('td:first', this).text());
         });
      });
   
   
      .selectedRow {
         background-color: blue;
         cursor: pointer;
      }
   


   <table border="1">
      <thead>
         <tr>
            <th>First column</th>
            <th>Second column</th>
            <th>Third column</th>
         </tr>
      </thead>
      <tbody>
         <tr>
            <td>This</td>
            <td>That</td>
            <td>The other</td>
         </tr>
         <tr>
            <td>Second</td>
            <td>line</td>
            <td>here</td>
         </tr>
      </tbody>
   </table>


So – I guess a brief explanation is in order. You’ll of course need the jQuery JavaScript library available in the correct location as referred to in the script tag (line 3). Apart from that, all the custom JavaScript jQuery code is happening in the script tag at the top of the page (lines 4 to 14). We are first creating a jQuery selector to select all tr tags inside a tbody tag which itself must reside within a table tag (line 6). When these tag elements are found we bind the ‘mouseover’, ‘mouseout’ and ‘click’ events to the rows (lines 6,8 and 10 respectively). The mouseover and mouseout event just add or remove a CSS class named ‘selectedRow’ dynamically to or from the row which adds the effect. The CSS class itself is defined at the top of the page within the style tags just after the script. The actual mouse click functionality just returns the value of the first cell in the selected row, just as an example. This could be a unique row id or similar.
The jQuery selector makes sure the mouse click event is set to only work on tr tags that are present from within a tbody tag to avoid adding the effect to the thead header row.

So that’s all there is to it really – not too bad. It was a lot simpler than I first imagined and the jQuery code makes things nice and tidy once you get used to the chained decorator pattern syntax.

11 thoughts on “Javascript mouseover effects on table rows using jQuery

  1. Or you could just add

    tr:hover {
    /** … */
    }

    to your CSS 😉

    But this (preferred) way of doing it is of course not supported by IE (other browsers will correctly support :hover on just about any HTML element), so you might want to try IE7.js for IE6-7 using “conditional comments” as well…

  2. A comment on my previous comment:

    This post does give a good example of what is easy to do with jQuery. The 2nd code snippet is so much cleaner than the 1st.

    Unfortunately, pure CSS’ hovering does not always suffice (thank you IE) … and sometimes – or perhaps always? – IE is that important to support. I recently had to do something similar myself, using jQuery to create a :hover effect on buttons (!) (where IE6 is *the* browser to support and IE7.js turned out to be out of the question).

  3. Hey dude, i see this is on wordpress.com. May i ask you how you got the highlighting syntax on the non-self hosted wordpress blog please.

    Also, nice code. Keep it up!

Leave a comment